#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "experiment_2_3_3.h"

/*
int main()
{
    List L;

    printf("Input elements (-1 to finish) : ");
    L = Initilize();
    Insert_Many(L)
    Traverse(L);

    int index;
    printf("Give one index: ");
    scanf(" %d", &index);
    printf("The value of given index is %d\n", FindKth(L, index));

    int value;
    printf("Give one value: ");
    scanf(" %d", &value);
    printf("The index of given value is %d\n", FindValue(L, value));

    int index_to_delete;
    printf("Give the index to delete: ");
    scanf(" %d", &index_to_delete);
    if (Delete(L, index_to_delete))
        printf("Deleted Success !\n");
    else
        printf("Deleted Failed !\n");
    Traverse(L);

    return 0;
}
*/

List Initialize()
{
    List L = (Position)malloc(sizeof(struct LNode));
    L->next = NULL;
    L->value = 0;

    return L;
}

bool Insert_Many(List L)
{
    int elements_to_insert, elements_count = 1;
    while (true)
    {
        scanf(" %d", &elements_to_insert);
        if (elements_to_insert == -1)
            break;
        Insert(L, elements_to_insert, elements_count++);
    }
    return true;
} 

void Traverse(List L)
{
    printf("The number of elements is %d\n", L->value);

    Position tmp = L;
    while (tmp->next != NULL) {
        tmp = tmp->next;
        printf("%d ", tmp->value);
    }
    printf("\n");
}

bool Insert(List L, int x, int index)
{
    Position tmp, pre;
    int cnt = 0;

    pre = L;
    while (pre && cnt < index - 1) {
        pre = pre->next;
        cnt++;
    }

    if (pre == NULL || cnt != index - 1) {          // position is not in the list
        printf("Wrong insert Position !\n");
        return false;
    } else {
        tmp = (Position)malloc(sizeof(struct LNode));
        tmp->value = x;
        tmp->next = pre->next;                      // new node point to previous node
        pre->next = tmp;
        L->value++;
        return true;
    }
    
}

int FindKth(List L, int K)
{
    Position p;
    int cnt = 0;
    p = L;
    while (p && cnt < K) {
        p = p->next;
        cnt++;
    }
    if (cnt == K)
        return p->value;
    else
        return ERROR;
}

int FindValue(List L, int value)
{
    Position p;
    int cnt = 1;
    p = L->next;
    while (p != NULL) {
        if (p->value == value)
            return cnt++;
        cnt++;
        p = p->next;
    }

    return ERROR;
}

bool Delete(List L, int index)
{
    Position p = L, tmp;
    int cnt = 0;
    
    while (p->next->next)
    {
        p = p->next;
        cnt++;
        if (cnt == index - 1) {
            tmp = p->next;
            p->next = tmp->next;
            free(tmp);
            L->value--;
            return true;
        }
    }

    return false;
}
